#coding=utf-8
import cv2
import os
import os.path as osp
import time
from datetime import datetime

def save_video_by_rtsp(save_dir, cap_ip, user, passwd, save_time):
    cap = cv2.VideoCapture("rtsp://{}:{}@{}:554/ch1/main/av_stream".format(user, passwd, cap_ip))
    print("ok")
    ret,frame = cap.read()
    print("ret: ", ret)
    if not ret: 
        return ret

    os.makedirs(save_dir, exist_ok=True)
    height, width = frame.shape[:2]
    fps = cap.get(5)
    print("fps: ", fps)
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
    name = '{}_{}.mp4'.format(cap_ip, datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))
    output_movie = cv2.VideoWriter(osp.join(save_dir, name), fourcc, 15, (int(width), int(height)))
    
    start_time = time.time()
    while True:
        ret,frame = cap.read()
        # cv2.imshow(cap_ip,frame)
        # cv2.waitKey(1)
        output_movie.write(frame)
        # if cv2.waitKey(1) & 0xFF == ord('q'): break

        if time.time() - start_time > save_time: break
           
    cap.release()
    output_movie.release()

if __name__ == '__main__':

    save_dir = "./video"
    cap_ip = "192.168.102.64"
    user = "admin"
    passwd = "abcd1234" 
    save_time = 5*60
    save_video_by_rtsp(save_dir, cap_ip, user, passwd, save_time)
